<?php

namespace Wap\Controller;

use Think\Log;
use Think\Model;

class IndexController extends \Think\Controller
{
    public function index()
    {
    	/* $is_weixin_client = O('Util')->isWxClient();
    	if (($is_weixin_client) || I('get.force_oauth')) {
           // Log::write('调用微信静默登录接口');
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
            //Log::write('调用微信静默登录接口---结果：'.json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);
        } */
       redirect('/kcadmin');
    }

    public function logo()
    {
        $url = get_cover(C('SITE_LOGO'), 'path');
        $url = $url && is_file('.' . $url) ? $url : '/Public/Wap/images/logo.png';
        redirect($url);
    }

    public function oauth()
    {
        $is_weixin_client = O('Util')->isWxClient();
        //throw new \Exception(I('get.jump_url','/'));
        // 当前oauth信息
        $oauthinfo = O('Kcdns\Service\User')->currentOauth() ?: "";

        // 微信环境自动获取 Oauth2 信息
       /* if (($is_weixin_client && !$oauthinfo) || I('get.force_oauth')) {
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
            O('Kcdns\Service\User')->setOauth($oauthinfo);
        }*/

        if (($is_weixin_client) || I('get.force_oauth')) {
            Log::write('调用微信静默登录接口');
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
            Log::write('调用微信静默登录接口---结果：'.json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);
        }

        redirect(I('get.jump_url','/'));
    }

    public function oauthSub(){
        $is_weixin_client = O('Util')->isWxClient();
        //throw new \Exception(I('get.jump_url','/'));
        // 当前oauth信息
        $oauthinfo = O('Kcdns\Service\User')->currentOauth() ?: "";

        // 微信环境自动获取 Oauth2 信息
        /* if (($is_weixin_client && !$oauthinfo) || I('get.force_oauth')) {
             $oauthinfo = O('Oauth')->getUserInfo('weixin');
             O('Kcdns\Service\User')->setOauth($oauthinfo);
         }*/


        if (($is_weixin_client) || I('get.force_oauth')) {
            Log::w_log('调用微信静默登录接口');
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
            Log::w_log('调用微信静默登录接口---结果：'.json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);
        }

        redirect(I('get.jump_url','/H5/login'));
    }

    public function wxReg()
    {
        $gzh_domain = getConfigValue('GZH_DOMAIN');
        $inviteCode = I('get.inviteCode');

        $is_weixin_client = O('Util')->isWxClient();
        $oauthinfo = O('Kcdns\Service\User')->currentOauth() ?: "";
        if (($is_weixin_client) || I('get.force_oauth')) {
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
//            Log::w_log('调用微信登录接口---结果：' . json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);


            //判断微信用户重复注册
            $user = M('oauth')->where([
                'openid' => $oauthinfo['openid'],
            ])->find();
            Log::w_log('绑定信息: uid'.$user['user_id']);
            if ($user['user_id']) {   //已注册
                M('user')->where(['uid' => $user['user_id']])->save(['avatar_url'=>$oauthinfo['user_info']['head']]);
                list($api_token, $expire_time) = OE('user')->genApiToken($user['user_id']);
                //重新绑定推荐人
                $user_info = M('user')->where(['uid' => $user['user_id']])->find();
                $refer = M('user')->where(['invite_code' => $inviteCode])->find();
                if($user_info['vip_level'] == 0 && $refer['uid'] != $user_info['uid'] && isset($refer['uid']) && $refer['vip_level']>0){
                    Log::w_log('bingd: uid'.$user['user_id']);
                    if($refer){
                        M('user')->where(['uid' => $user_info['uid']])->save(['referer_id' => $refer['uid']]);
                    }
                }
                redirect(I('get.jump_url', $gzh_domain ."/login_back_url?msg=".urlencode('登录成功')."&t=2")
                    ."&token=".urlencode($api_token)."&expire_time={$expire_time}"
                    ."&invite_code={$user['invite_code']}"
                );
            } else {
                /*if(!$inviteCode){
                    redirect(I('get.jump_url', "/H5/tishi?msg=".urlencode('推荐人为空')));
                }
                $invite_user_data = M('user')->where(['invite_code' => $inviteCode])->find();
                if($invite_user_data['vip_level']<1){
                    redirect(I('get.jump_url', "/H5/tishi?msg=".urlencode('推荐人必须是VIP以上')));
                }*/
                $param = array(
                    'password' => '123456',
                    'invite_code' => $inviteCode,
                    'head' => $oauthinfo['user_info']['head'],
                    'nickname' => $oauthinfo['user_info']['nickname'],
                );
                $result = OE('user')->register2($param);
                if ($result['code'] != 0) {
                    redirect(I('get.jump_url', "/H5/tishi?msg={$result['msg']}&openid={$oauthinfo['openid']}"));
                }else{
                    Log::w_log(json_encode($result));
                    list($api_token, $expire_time) = $result['data']['api_token'];
                    redirect(I('get.jump_url', $gzh_domain . "/login_back_url?msg=".urlencode('登录成功')."&t=2")
                    ."&token=".urlencode($api_token)."&expire_time={$expire_time}"
                        ."&invite_code={$result['data']['invite_code']}"
                    );
                }
            }

        } else {
            redirect(I('get.jump_url', $gzh_domain.'/login'));
        }

    }


    public function wxRegOld()
    {
        $inviteCode = I('get.inviteCode');

        $is_weixin_client = O('Util')->isWxClient();
        $oauthinfo = O('Kcdns\Service\User')->currentOauth() ?: "";
        if (($is_weixin_client) || I('get.force_oauth')) {
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
//            Log::w_log('调用微信登录接口---结果：' . json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);


            //判断微信用户重复注册
            $user = M('oauth')->where([
                'openid' => $oauthinfo['openid'],
            ])->find();
            Log::w_log('绑定信息: uid'.$user['user_id']);
            if ($user['user_id']) {   //已注册
                M('user')->where(['uid' => $user['user_id']])->save(['avatar_url'=>$oauthinfo['user_info']['head']]);
                redirect(I('get.jump_url', '/H5/tishi?msg='.urlencode('已注册')."&openid={$oauthinfo['openid']}&t=1"));
            } else {
                /*if(!$inviteCode){
                    redirect(I('get.jump_url', "/H5/tishi?msg=".urlencode('推荐人为空')));
                }
                $invite_user_data = M('user')->where(['invite_code' => $inviteCode])->find();
                if($invite_user_data['vip_level']<1){
                    redirect(I('get.jump_url', "/H5/tishi?msg=".urlencode('推荐人必须是VIP以上')));
                }*/
                $param = array(
                    'password' => '123456',
                    'invite_code' => $inviteCode,
                    'head' => $oauthinfo['user_info']['head'],
                    'nickname' => $oauthinfo['user_info']['nickname'],
                );
                $result = OE('user')->register2($param);
                if ($result['code'] != 0) {
                    redirect(I('get.jump_url', "/H5/tishi?msg={$result['msg']}&openid={$oauthinfo['openid']}"));
                }else{
                    Log::w_log(json_encode($result));
                    list($api_token, $expire_time) = $result['data']['api_token'];
                    redirect(I('get.jump_url', "/H5/tishi?msg=".urlencode('登录成功')."&t=2")
                        ."&token=".urlencode($api_token)."&expire_time={$expire_time}"
                        ."&invite_code={$result['data']['invite_code']}"
                    );
                }
            }

        } else {
            redirect(I('get.jump_url', '/'));
        }

    }

    public function wxLogin(){
        $is_weixin_client = O('Util')->isWxClient();
        if (($is_weixin_client) || I('get.force_oauth')) {
            $oauthinfo = O('Oauth')->getUserInfo('weixin');
//            Log::w_log('调用微信登录接口---结果：' . json_encode($oauthinfo));
            O('Kcdns\Service\User')->setOauth($oauthinfo);
            redirect(I('get.jump_url', '/H5/wxlogin?openid='.$oauthinfo['openid']));
        } else {
            redirect(I('get.jump_url', '/'));
        }
    }



    public function test(){
        $data = M('user')->where(['uid' => 7102])->find();
        $phpexc = new \PHPExcel();
        var_dump($data);
    }



    public function pay()
    {
        $data = [
            'orderNo' => '0346566516026971', // 订单号
            'amount' => 255, // 支付金额
            'payType' => 'aliwappay', // 支付类型 Weixin Alipay
//            'callback' => 'payCallback', // 支付成功业务回调
            'redirectUrl' => "http://{$_SERVER['HTTP_HOST']}", // 支付成功后跳转地址
            'orderTitle' => '测试订单', // 订单名称
        ];
        $pay_url = OE('pay')->pay($data);
        echo $pay_url;
    }

    public function te()
    {
        var_dump(222222222222222222);
        exit();
        $uid = 7183;
        $referer_id = 4158;
        if (SPEED_API_OPEN) {
            $Model = new Model();
            $user_ucenter_data = $Model->table('__UCENTER_MEMBER__')->where(array('id'=>$uid))->find();
            $referer_ucenter_data = $Model->table('__UCENTER_MEMBER__')->where(array('id'=>$referer_id))->find();
            //加速中心同步注册
            $api_data = [
                'company' => SPEED_API_CLIENT,
                'req_time' => time(),
                'username' => $user_ucenter_data['username'],
                'referer' => $referer_ucenter_data['username'],
            ];
            $response = OE('util')->curl(SPEED_API_HOST . '/Wap/api/register', array_merge($api_data, [
                'sign' => $this->genSign($api_data)
            ]));
            $result = json_decode($response, true);
            if ($result['status'] != 1) {
                $ret = array('code' => -1, 'msg' => '同步注册失败,请联系管理员');
//                        return $ret;
                var_dump('同步成功');
            }else{
                var_dump('同步失败');
            }
        }

        exit();



        $data = array(
            'openid' => 'oVNGS1eaKWucNy0ERB7E3LlYcNzg',
            'productType' => '会员账号',
            'name' => 'qc18121200001',
            'account' => '满又琳',
            'remark' => '满又琳！qc18121200001，以便于转账给她支付 '
        );
        $result = OE('wx')->sendWxMsg('4-4eUi8xUn_h-TmMOH7o4AzM2rFxKqjteuE1KMeRhiY', $data);
        Log::w_log("########start########");
    }

    public function getLocation()
    {
    	$list = O('Common')->getAreaDict();
    	exit(json_encode($list, JSON_UNESCAPED_UNICODE));
    }

    public function orderLogisticsSearch(){
        //参数设置
        $type = $_GET['type'];
        $post_data = array();
        $post_data["customer"] = 'C50176B30C03B00914DE024974D21D8B';
        $key= 'cQsCyegH282' ;
        $post_data["param"] = '{"com":"'.$type.'","num":"960146726663"}';

        $url='http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        $data = str_replace("\"",'"',$result );
        $data = json_decode($data,true);
        var_dump($data);
    }

    public function daoUser()
    {

        $model = new Model();
        $ding_uid = 4317;
        $result = [];
        $user_data =  $model->table('__USER__ as u')
            ->field('u.uid, u.total_contribution, u.total_self_buy, u.referer_id,
                 m.username, m.password, m1.username as re_username')
            ->join('__UCENTER_MEMBER__ as m on u.uid=m.id')
            ->join('__UCENTER_MEMBER__ as m1 on u.referer_id=m1.id')
            ->where([
                'm.id' => [['egt', $ding_uid]],
            ])
            ->select();



        foreach($user_data as &$item) {
            $uid = $item['referer_id'];
            while(true){
                $user = $model->table('__USER__')
                    ->where(['uid' => $uid])
                    ->find();
                if($user['uid'] == $ding_uid){
                    $result[] = $item;
                    break;
                }
                if(!$user){
                    break;
                }
                $uid = $user['referer_id'];
                Log::w_log("@@@@@@uid:".$uid);
            }

        }

        $file = fopen(ROOT_PATH .'Data/user6668888.xls', 'w');
        fwrite($file, "uid\tusername\tpassword\tre_username\treferer_id\timport_comport\t\n");

        foreach ($result as &$item) {
            fwrite($file, $item['uid']."\t".$item['username']."\t".$item['password']."\t".$item['re_username']."\t".$item['referer_id']."\t6\t\n");//这里写得不好，应该把所有文件内容组装到一个字符串中然后一次性写入文件。
        }

        fclose($file);

        echo "success";exit();
    }

    public function daoUser1()
    {

        $model = new Model();
        $sql = "SELECT * FROM k_user WHERE vip_level>0;";
        $user_data =  $model->query($sql);
        $file = fopen(ROOT_PATH .'Data/user6668888.xls', 'w');
        fwrite($file, "uid\tusername\tpassword\tre_username\treferer_id\timport_comport\t\n");

        foreach ($user_data as &$item) {
            fwrite($file, $item['uid']."\t".$item['username']."\t".$item['password']."\t".$item['re_username']."\t".$item['referer_id']."\t6\t\n");//这里写得不好，应该把所有文件内容组装到一个字符串中然后一次性写入文件。
        }

        fclose($file);

        echo "success";exit();
    }

    public function dd(){
        $model = new Model();
        $sql = "SELECT u.uid,m.username,m1.username as re_username FROM `k_user` as u
LEFT JOIN k_ucenter_member as m1 ON m1.id=u.referer_id
LEFT JOIN k_ucenter_member as m ON m.id=u.uid WHERE u.vip_level>0 ORDER BY u.uid;";
        $user_data =  $model->query($sql);
        $this->ajaxReturn($user_data, 'JSON');
    }
}
